﻿using HANS.WeChat.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.RegisterServices;

namespace WeChatSite
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //添加Weixin配置文件（内容可以根据需要对应修改）
            services.Configure<HANSWeChatSetting>(Configuration.GetSection("HANSWeChatSetting"))
                    //Weixin全局注册
                    .AddSernparcWeixinGlobalServices();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<HANSWeChatSetting> wechatsetting)
        {
            if (env.IsDevelopment())
            {
                // app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                //app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "WeChatBlog", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(name: "WeChat", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            #region 微信相关配置
            #region 提供网站根目录
            if (env.ContentRootPath != null)
            {
                Server.AppDomainAppPath = env.ContentRootPath;// env.ContentRootPath;
            }
            Server.WebRootPath = env.WebRootPath;// env.ContentRootPath;
            #endregion

            var isDebug = true;//当前是否是Debug状态
            RegisterService.Start(env, wechatsetting, isDebug)
            #region 缓存配置

                // 当同一个分布式缓存同时服务于多个网站（应用程序池）时，可以使用命名空间将其隔离（非必须）
                .ChangeDefaultCacheNamespace("HANSWeChatCache")



            #endregion

            #region 注册日志（按需）

                .RegisterTraceLog(ConfigWeixinTraceLog) //配置TraceLog

            #endregion
            #region 注册线程（必须）

                 .RegisterThreads()  //启动线程

            #endregion
            #region 注册公众号或小程序（按需）

                //注册公众号
                .RegisterMpAccount(
                    wechatsetting.Value.WeixinAppId,
                    wechatsetting.Value.WeixinAppSecret,
                    "公众号")
                //注册多个公众号或小程序
                .RegisterMpAccount(
                    wechatsetting.Value.WxOpenAppId,
                    wechatsetting.Value.WxOpenAppSecret,
                    "小程序");

            #endregion
            #endregion
        }

        /// 配置微信跟踪日志
        /// </summary>
        private void ConfigWeixinTraceLog()
        {
            //这里设为Debug状态时，/App_Data/WeixinTraceLog/目录下会生成日志文件记录所有的API请求日志，正式发布版本建议关闭
            Senparc.Weixin.Config.IsDebug = true;
            Senparc.Weixin.WeixinTrace.SendCustomLog("系统日志", "系统启动");//只在Senparc.Weixin.Config.IsDebug = true的情况下生效

            //自定义日志记录回调
            Senparc.Weixin.WeixinTrace.OnLogFunc = () =>
            {
                //加入每次触发Log后需要执行的代码
            };
            //当发生基于WeixinException的异常时触发
            Senparc.Weixin.WeixinTrace.OnWeixinExceptionFunc = ex =>
            {

            };
        }
    }
}
